package com.agileai.miscdp.hotweb.ui.actions.standard;

import java.lang.reflect.InvocationTargetException;
import java.util.List;

import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.progress.IProgressService;

import com.agileai.miscdp.DeveloperConst;
import com.agileai.miscdp.hotweb.database.DBManager;
import com.agileai.miscdp.hotweb.database.SqlBuilder;
import com.agileai.miscdp.hotweb.domain.Column;
import com.agileai.miscdp.hotweb.domain.ProjectConfig;
import com.agileai.miscdp.hotweb.domain.standard.StandardFuncModel;
import com.agileai.miscdp.hotweb.ui.actions.BaseInitGridAction;
import com.agileai.miscdp.hotweb.ui.editors.standard.SMBasicConfigPage;
import com.agileai.miscdp.hotweb.ui.editors.standard.StandardModelEditor;
import com.agileai.miscdp.hotweb.ui.editors.standard.StandardModelEditorContributor;
import com.agileai.miscdp.util.DialogUtil;
import com.agileai.miscdp.util.MiscdpUtil;
import com.agileai.util.StringUtil;
/**
 * 初始化表中功能模型数据
 */
public class SMInitGridAction extends BaseInitGridAction{
	private SMBasicConfigPage basicConfigPage;
	private String tableName;
	private Text sqlText;
	public SMInitGridAction() {
	}
	public void setContributor(StandardModelEditorContributor contributor) {
		this.contributor = contributor;
	}
	private String getPkGenPolicy(String tableName){
		String result = "";
		String projectName = modelEditor.getFuncModel().getProjectName();
		Column[] columns = DBManager.getInstance(projectName).getColumns(tableName);
		if (columns != null && columns.length > 0){
			int count = columns.length;
			for (int i=0;i < count;i++){
				Column column = columns[i];
				if (column.isPK()){
					if ("java.lang.Integer".equals(column.getClassName())
							|| "java.lang.Long".equals(column.getClassName())){
						result = Column.PKType.INCREASE;
						break;
					}
					else if ("java.lang.String".equals(column.getClassName())){
						if (column.getLength() == 36){
							result = Column.PKType.CHARGEN;
							break;
						}
						else{
							result = Column.PKType.ASSIGN;
							break;
						}
					}
				}
			}
		}
		return result;
	}
	public void run() {
		IWorkbenchPage workbenchPage = contributor.getPage();
		IEditorPart editorPart = workbenchPage.getActiveEditor();
		modelEditor = (StandardModelEditor)editorPart;
		basicConfigPage = ((StandardModelEditor)modelEditor).getBasicConfigPage();
		Combo tableNameCombo = basicConfigPage.getTableNameCombo();
		String tableName = tableNameCombo.getText();
		Shell shell = modelEditor.getSite().getShell();
		if (StringUtil.isNullOrEmpty(tableName)){
			DialogUtil.showMessage(shell,"消息提示","请先选择数据表!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		String funcSubPkg = basicConfigPage.getFuncSubPkgText().getText();
		if (StringUtil.isNullOrEmpty(funcSubPkg)){
			DialogUtil.showMessage(shell,"消息提示","目录编码不能为空!",DialogUtil.MESSAGE_TYPE.WARN);
			return;
		}
		String projectName = modelEditor.getFuncModel().getProjectName();
		this.tableName = tableNameCombo.getText();
		String[] primaryKeys = DBManager.getInstance(projectName).getPrimaryKeys(tableName);
		if (primaryKeys == null){
			MessageDialog.openInformation(shell, "消息提示","所选择的数据表没有主键!");
			return;
		}
		boolean doInitGrid = MessageDialog.openConfirm(shell,"消息提示","自动填写可能会覆盖已有内容，是否继续!");
		if (!doInitGrid){
			return;
		}
		
		sqlText = ((StandardModelEditor)modelEditor).getBasicConfigPage().getListSqlText();
        IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
        IRunnableWithProgress runnable = new IRunnableWithProgress() {
			public void run(IProgressMonitor monitor) throws InvocationTargetException {
				try {
					doRun(monitor);
				} catch (Exception e) {
					throw new InvocationTargetException(e);
				} finally {
					monitor.done();
				}
			}
        };
        try {
			progressService.runInUI(PlatformUI.getWorkbench().getProgressService(),
					runnable,ResourcesPlugin.getWorkspace().getRoot());
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
	
	@SuppressWarnings("unchecked")
	public void doRun(IProgressMonitor monitor) {
		monitor.beginTask("init grid values....", 1000);
		monitor.subTask("init basic values....");
		monitor.worked(50);
		((StandardModelEditor)modelEditor).buildFuncModel();
		StandardFuncModel suFuncModel = ((StandardModelEditor)modelEditor).getFuncModel();
		try {
			String funcSubPkg = basicConfigPage.getFuncSubPkgText().getText();
			suFuncModel.setTableName(tableName);
			suFuncModel.setFuncSubPkg(funcSubPkg);
			
			String pkGenPolicy = getPkGenPolicy(tableName);
			suFuncModel.setPkGenPolicy(pkGenPolicy);
			String namePrefix = MiscdpUtil.getValidName(tableName);
			String beanIdPrefix = namePrefix.substring(0,1).toLowerCase()+namePrefix.substring(1,namePrefix.length());
			
			suFuncModel.setListJspName(funcSubPkg +"/"+namePrefix+"ManageList.jsp");
			suFuncModel.setDetailJspName(funcSubPkg +"/"+namePrefix+"ManageEdit.jsp");
			String funcName = suFuncModel.getFuncName();
			suFuncModel.setListTitle(funcName);
			suFuncModel.setDetailTitle(funcName);
			suFuncModel.setServiceId(beanIdPrefix+"ManageService");
			
			String projectName = suFuncModel.getProjectName();
			ProjectConfig projectConfig = new ProjectConfig();
			String configFile = MiscdpUtil.getCfgFileName(projectName,DeveloperConst.PROJECT_CFG_NAME);
			projectConfig.setConfigFile(configFile);
			projectConfig.initConfig();
			String mainPkg = projectConfig.getMainPkg();
			suFuncModel.setImplClassName(mainPkg +".bizmoduler."+funcSubPkg+"."+namePrefix +"ManageImpl");
			suFuncModel.setInterfaceName(mainPkg +".bizmoduler."+funcSubPkg+"."+namePrefix+"Manage");
			
			DBManager dbManager = DBManager.getInstance(projectName);
			SqlBuilder sqlBuilder = new SqlBuilder();
			String[] colNames = MiscdpUtil.getColNames(dbManager, tableName);
            String listSql = sqlBuilder.findAllSql(tableName,colNames);
            listSql =  listSql + " where 1=1";
            suFuncModel.setListSql(listSql);
			String curListSql = sqlText.getText(); 
            if (curListSql == null || curListSql.trim().equals("")){
            	sqlText.setText(listSql);
            }
            else{
            	int lastWhereIndex = curListSql.toLowerCase().indexOf("where");
            	if (lastWhereIndex > 0){
            		String lashWhere = curListSql.substring(lastWhereIndex,listSql.length());
					List<String> params = MiscdpUtil.getParams(lashWhere);
            		StandardFuncModel.initPageParameters(params,suFuncModel.getPageParameters());
            	}
            }
			
			suFuncModel.setExportCsv(true);
			suFuncModel.setExportXls(true);
			suFuncModel.setSortAble(true);
			suFuncModel.setPagination(true);

			monitor.subTask("init list grid values....");
			monitor.worked(300);
			Column[] columns = dbManager.getColumns(tableName);
			
			StandardFuncModel.initListTableColumns(columns, suFuncModel.getListTableColumns(), suFuncModel.getRsIdColumns());

			
			monitor.subTask("init form grid values....");
			monitor.worked(800);
			
			StandardFuncModel.initPageFormFields(columns, suFuncModel.getPageFormFields(),null);
		} catch (Exception e) {
			e.printStackTrace();
		}
		modelEditor.initValues();
		
		monitor.subTask("refresh viewer....");
		monitor.worked(900);
		
		TableViewer paramTableViewer = ((StandardModelEditor)modelEditor).getListJspCfgPage().getPageParamTableViewer();
		paramTableViewer.setInput(suFuncModel.getPageParameters());
		paramTableViewer.refresh();
		
		TableViewer columnTableViewer = ((StandardModelEditor)modelEditor).getListJspCfgPage().getColumnTableViewer();
		columnTableViewer.setInput(suFuncModel.getListTableColumns());
		columnTableViewer.refresh();
		
		TableViewer tableViewer = ((StandardModelEditor)modelEditor).getDetailJspCfgPage().getTableViewer();
		tableViewer.setInput(suFuncModel.getPageFormFields());
		tableViewer.refresh();
		return;
	}
}
